package com.pan.admin.module.api.lock.impl;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pan.admin.module.api.lock.ApiKeyBalanceOperationLock;

/**
 * @author caoxin
 */
@Component
public class ApiKeyBalanceOperationLockImpl implements ApiKeyBalanceOperationLock {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public <T> T executeInLock(String apiClientId, Supplier<T> supplier) {
        Objects.requireNonNull(apiClientId);
        RLock lock = redissonClient.getLock("api_key_bill_lock:" + apiClientId);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            return supplier.get();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void executeInLock(String apiClientId, Runnable runnable) {
        this.executeInLock(apiClientId, () -> {
            runnable.run();
            return null;
        });
    }

}
